import base64
import binascii
from datetime import date

from django.utils.translation import gettext_lazy as _

from rest_framework.authentication import get_authorization_header
from rest_framework import exceptions


def basic_decode_user(request):
    auth = get_authorization_header(request).split()

    if not auth:
        msg = _('Invalid basic header. No credentials provided.')
        raise exceptions.AuthenticationFailed(msg)

    if len(auth) == 1:
        msg = _('Invalid basic header. No credentials provided.')
        raise exceptions.AuthenticationFailed(msg)
    elif len(auth) > 2:
        msg = _('Invalid basic header. Credentials string should not contain spaces.')
        raise exceptions.AuthenticationFailed(msg)
    try:
        try:
            auth_decoded = base64.b64decode(auth[1]).decode('utf-8')
        except UnicodeDecodeError:
            auth_decoded = base64.b64decode(auth[1]).decode('latin-1')
        auth_parts = auth_decoded.partition(':')
    except (TypeError, UnicodeDecodeError, binascii.Error):
        msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
        raise exceptions.AuthenticationFailed(msg)

    userid, password = auth_parts[0], auth_parts[2]
    return userid, password

